import os
import gpio
import mqtt
import LedClass
from harmonyTest import CurtainClass

# import curtainclass

host = '192.168.137.1'
port = 1883

n = mqtt.net_connect(host, port)

print('n = ', n)

# 1st param is network id
# 2nd param is the tx and rx buffer size, default value is 256
# 3rd param is the timeout value (ms), default value is 2000
# c = mqtt.client_init(n, 256, 2000)
c = mqtt.client_init(n)

print('c = ', c)

cd = mqtt.ConnData()

cd.mqtt_version = 3
cd.clean_session = 1
cd.client_id = 'emqx_test'
cd.keep_alive = 60
cd.username = ''
cd.password = '12345678'

print(cd.mqtt_version)
print(cd.clean_session)
print(cd.client_id)
print(cd.keep_alive)
print(cd.password)

r = mqtt.connect(c, cd)

print('r = ', r)

mp = mqtt.MsgParam()

mp.qos = 2
mp.retain = 0
mp.dup = 0
mp.id = 0

win_topic = 'testtopic/delphi/tang/test'
light_topic = 'light/test'


light = LedClass.Led(7)


# arg[0] ==> MsgParam object
# arg[1] ==> string object
# arg[2] ==> list object contained byte values
def callback(arg):
    print('param = ', arg[0])
    print('id = ', arg[0].id)
    print('qos = ', arg[0].qos)
    print('dup = ', arg[0].dup)
    print('retain = ', arg[0].retain)
    print('topic = ', arg[1])
    print('payload = ', str(bytes(arg[2]), 'ascii'))
    if arg[1] == win_topic:
        CurtainClass.win_callback(None)

    if arg[1] == light_topic:
        if str(bytes(arg[2]), 'ascii') == 'on':
            light.on()
        if str(bytes(arg[2]), 'ascii') == 'off':
            light.off()


# 1st param is client id
# 2nd param is the topic string
# 3rd param is the qos value
# 4th param is the callback function
r = mqtt.subscribe(c, win_topic, 2, callback)
# r = mqtt.subscribe(c, light_topic, 2, callback)

print('r = ', r)

print('jskad')

while mqtt.is_connected(c):
    os.handle_event()
    os.sleep(200)

# finialize resource
r = mqtt.unsubscribe(c, win_topic)
# r = mqtt.unsubscribe(c, light_topic)

print('r = ', r)

r = mqtt.disconnect(c)

print('r = ', r)

r = mqtt.client_deinit(c)

print('r = ', r)

r = mqtt.net_disconnect(n)

print('r = ', r)

